package com.xjy.rpc.netty.client;

import com.xjy.rpc.netty.handler.RpcEncoder;
import com.xjy.rpc.netty.handler.RpcDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.ExecutionException;

public class ClientTest {
    public static void main(String[] args) {
        ClientTest clientTest = new ClientTest();
        clientTest.run();
        clientTest.sendMessage("hello");
    }

    private Channel channel;

    private NioEventLoopGroup worker;

    public void run(){
        Bootstrap bs = new Bootstrap();
        worker = new NioEventLoopGroup();

        ChannelFuture future = bs.group(worker).channel(NioSocketChannel.class)
                //设置检测连接
                .option(ChannelOption.SO_KEEPALIVE, true)
                //设置端口复用
                .option(ChannelOption.SO_REUSEADDR, true)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new RpcEncoder());
                        pipeline.addLast(new RpcDecoder());
                    }
                }).connect("127.0.0.1", 8083);

        try {
            future.get();
            channel = future.channel();
            System.out.println("客户端连接成功");
        } catch (InterruptedException e) {
            shutdown();
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    public void sendMessage(String msg){
        channel.writeAndFlush(msg);
    }

    public void shutdown(){
        if (worker != null) worker.shutdownGracefully();
    }
}
